<template>
	<om-addpage style="padding-top: 35px;" :menuName="menuName" @formSubmit="formSubmit" :busCode="busCode">
		<om-autoform ref="autoform" :initConfigData="mainConfigData" :initValue="initValue"></om-autoform>
	</om-addpage>
</template>

<script>
	import {
		getUrl,
		confirmModal,
		errorModal,
		ptFloat,
		minusF
	} from '@/static/js/common.js';
	import {
		buildFormData,
		formValidation,
		tranferToEditors,
		changeEditor,
		setSubmitSubValue,
		configSelectData,
		hasValue,
		hasEditor,
		getEditorTitle,
		changeConfigAttr,
		formShowLoading,
		getFormFields,
		formModelLoad,
		getWorkCacheKey
	} from '@/static/js/formUtil.js';
	import urlUtil from '@/static/js/urlUtil.js';
	import { mapState } from 'pinia';
	import {useLoginUserStore} from '@/stores/login-user.js';

	export default {
		data() {
			return buildFormData({
				userCacheKey: "hr-kq-business-user-cache",
				infoCacheKey: 'hr-kq-business-info-cache',
				InstCacheKey: "hr-kq-business-inst-cache",
				sameOutUserCache: "hr-kq-business-sameOutUser-cache",
				defaultDataCache: 'hr-kq-business-sameOutUser-defaultDataCache-cache',
				userId1: "",
				editId: "",
				infoId: "",
				fileKey: '42',
				businessTripTypeCode: ''
			})
		},
		computed: {
			...mapState(useLoginUserStore, ['userName', 'userId'])
		},
		provide() {
			return {
				formPage: this
			}
		},
		methods: {
			onselectBusinessTripType(data){
				let _that = this
				let formdata = _that.$refs.autoform.formdata
				if(_that.subEditorObj['workOfficeInfo']){
					let dataList = _that.subEditorObj['workOfficeInfo'].workList
					for(let index in dataList){
						dataList[index].leaveCountryId = data.id
						dataList[index].leaveCountryName = data.dicname
					}
					formdata.dataStr = JSON.stringify(dataList)
					if(_that.subEditorObj['workOfficeInfo']){
						_that.subEditorObj['workOfficeInfo'].workList = dataList
					}
					if(dataList.length > 0){
						_that.om.toast('子表数据已更新')
					}
					
					uni.setStorageSync('omBusinessTripType', data.code)
					_that.businessTripTypeCode = data.code
				}
			},
			clearBusinessTripType(){
				let _that = this
				_that.$refs.autoform.clear('InfoTitle', 'businessTripTypeId');
				let formdata = _that.$refs.autoform.formdata
				if(_that.subEditorObj['workOfficeInfo']){
					let dataList = _that.subEditorObj['workOfficeInfo'].workList
					let flag = true;
					for(let i=0;i<dataList.length;i++){
						if(dataList[i].leaveCountryId){
							flag = false;
						}
					}
					if(flag){
						uni.setStorageSync('omBusinessTripType', '39415')
						_that.businessTripTypeCode = '39415'
					}
				}
			},
			verifyWorkOffice() {
				let _that = this
				if (!_that.$refs.autoform.formdata.infoId) {
					let title = _that.$refs.autoform.getEditorTitle("InfoTitle", "infoId")
					_that.om.toast("请先选择" + title)
					return false
				} else {
					return true
				}
			},
			verifySameOutUser() {
				let _that = this
				if (!_that.$refs.autoform.formdata.infoId) {
					let title = _that.$refs.autoform.getEditorTitle("InfoTitle", "infoId")
					_that.om.toast("请先选择" + title)
					return false
				} else {
					return true
				}
			},
			getUserSalaryPosInfo(id) {
				let _that = this
				_that.om.request(
					"orgInstPosUserOfficial/getUserSalaryPosInfo", {
						userId: id
					}
				).then(res => {
					_that.$refs.autoform.formdata.salaryPosName = res.value.posName
					_that.$refs.autoform.formdata.rinstName = res.value.instName
					_that.$refs.autoform.formdata.parentUserName = res.value.parentUserName
					
					_that.om.request(
						"tinstitution/getInstInfo",
						{
							instId:res.value.instId
						}
					).then(res=>{
						_that.$refs.autoform.formdata.rinstLevelId =  res.value.instcatId
						_that.$refs.autoform.formdata.rinstLevelName =  res.value.instcatName
					})
				})
			},
			getWorkParam() {
				let _that = this
				return {
					userId: _that.$refs.autoform.formdata.infoId,
					editId: _that.editId,
					objStr: JSON.stringify(_that.subEditorObj['workOfficeInfo'].workList),
					businessTripTypeId:_that.$refs.autoform.formdata.businessTripTypeId,
					businessTripTypeName:_that.$refs.autoform.formdata.businessTripTypeName,
					businessTripTypeCode:_that.businessTripTypeCode,
				}
			},
			initLoad(options) {
				let _that = this;
				var fileId = options.fileId
				let ajaxArr = [
					urlUtil.sysdictComboboxUrl("30061"),
					{
						url: "tworkoffice/getTitleInfo"
					},
					urlUtil.dictZeroComboboxUrl('36924'),
					{
						url: "wxPosBusiAuth/isnewList",
						param: {
							code: "HRS1203"
						},
						method: "post"
					},
					urlUtil.dictZeroComboboxUrl('39414'),
				]
				//表单修改
				if (fileId) {
					_that.editId = fileId
					ajaxArr.push({
						url: "tworkoffice/getInfo",
						param: {
							id: fileId
						}
					})
				}
				formModelLoad(ajaxArr, function(res, mainData) {
					changeEditor('InfoTitle', 'businessTripTypeId', 'data', configSelectData(res[4], 'id','dicname'), mainData);
					changeEditor('topinfo', 'zposId', 'data', configSelectData(res[3], 'id', 'posName'), mainData)
					if (_that.subEditorObj["workOfficeInfo"]) {
						let att = {
							getWorkParam: "getWorkParam"
						}
						let configData = _that.subConfigData['workOfficeInfo']
						if (hasEditor("workOfficeInfo", "startTime", configData)) {
							let title = getEditorTitle("workOfficeInfo", 'startTime', configData)
							att.titleTemplate = "<%= startTime%>~"
						}
						if (hasEditor("workOfficeInfo", "endTime", configData)) {
							let title = getEditorTitle("workOfficeInfo", 'endTime', configData)
							att.titleTemplate += "<%= endTime%>"
						}
						if (hasEditor("workOfficeInfo", "departureCityId", configData)) {
							let title = getEditorTitle("workOfficeInfo", 'departureCityId', configData)
							att.subtitle1Template = title + ":<%= departureCityName%>"
						}
						if (hasEditor("workOfficeInfo", "addressId", configData)) {
							let title = getEditorTitle("workOfficeInfo", 'addressId', configData)
							att.subtitle2Template = title + ":<%= addressName%>"
						}
						if (hasEditor("workOfficeInfo", "vehicleCode", configData)) {
							let title = getEditorTitle("workOfficeInfo", 'vehicleCode', configData)
							att.subtitle3Template = title + ":<%= vehicleName%>"
						}
						changeEditor('workOfficeInfo', 'objStr', att, mainData)
						changeEditor('topinfo', 'zuserId', {
							defaultName: _that.userName,
							defaultValue: _that.userId
						}, null, mainData);
					}
					changeEditor("InfoTitle", "infoId", {
						link: "../../public/pageSearch/pageSearch",
						"linkParam": {
							other: JSON.stringify({}),
							namefield: urlUtil.findUserAsSameInst().namefield,
							extrafield: urlUtil.findUserAsSameInst().extrafield,
							searchfield: "q",
							url: urlUtil.findUserAsSameInst().url,
							cachename: _that.infoCacheKey,
							initload: true,
							placeholder: "请输入姓名"
						}
					}, null, mainData)

					changeEditor('InfoTitle', 'sameOutUserId', 'isSearchUser', true, mainData);
					changeEditor('InfoTitle', 'sameOutUserId', {
						'link': '../../public/searchUser/searchUser',
						linkParam: {
							namefield: urlUtil.userPageUrl().namefield,
							searchfield: "q",
							cachename: _that.sameOutUserCache,
							defaultDataCache: _that.defaultDataCache,
							isNew: true,
							defaultData: 'searchUserDefaultData',
							placeholder: urlUtil.userPageUrl().prompt,
							pagination: true
						}
					}, null, mainData);
					changeEditor("timeAndCost", "moneyUnitId", "data", configSelectData(res[0], "id", "dicname"),
						mainData)

					changeEditor("InfoTitle", "costInstId", {
						link: "../../public/search/search",
						"linkParam": {
							other: JSON.stringify({
								containBoard: true
							}),
							method: "post",
							namefield: 'instName',
							searchfield: "q",
							initload: true,
							url: 'tinstitution/findNotBoard1',
							cachename: _that.InstCacheKey,
							placeholder: "请输入部门名称"
						}
					}, null, mainData)
					changeEditor('InfoTitle', 'privateCarPublicUseId', 'data', configSelectData(res[2], 'id',
						'dicname'), mainData);

					_that.$set(_that.formdata, "titleInfo", res[1].value)
					changeConfigAttr("workOfficeInfo", "subTitle", res[1].value, mainData)
					let tempFileList = []
					let fileUrlList = []
					changeEditor('bottominfo', 'bottomFileUpload', 'fileUploadKey', "42", mainData)
					changeEditor("bottominfo", "bottomFileUpload", "tempFileList", tempFileList, mainData)
					changeEditor("bottominfo", "bottomFileUpload", "fileUrlList", fileUrlList, mainData)
					//子表
					if (fileId) {
						var fieldArr = getFormFields(mainData)
						fieldArr.push("id")
						for (var i in res[5].value.tworkOffice) {
							if (fieldArr.includes(i)) {
								_that.$refs.autoform.$set(_that.$refs.autoform.formdata, i, res[5].value
									.tworkOffice[i])
								_that.$set(_that.formdata, i, res[5].value.tworkOffice[i])
							}
						}
						var dataList = _that._.cloneDeep(res[5].value.tworkOffice_data)
						if (_that.subEditorObj["workOfficeInfo"]) { //配置子表的新增和删除
							_that.subEditorObj["workOfficeInfo"].workList = dataList
							_that.$refs.autoform.$set(_that.$refs.autoform.formdata, "objStr", JSON.stringify(
								dataList))
							_that.$set(_that.formdata, "objStr", JSON.stringify(dataList))
							delete res[5].value.dataList
							if (_that.formdata.bottomFileList) {
								let tempFileList = []
								let fileUrlList = _that.formdata.bottomFileList.map(t => {
									tempFileList.push(t.fileSaveName)
									return t.fileSaveName
								})
								changeEditor("bottominfo", "bottomFileUpload", "tempFileList", tempFileList,
									mainData)
								changeEditor("bottominfo", "bottomFileUpload", "fileUrlList", fileUrlList,
									mainData)
							}

							changeEditor("workOfficeInfo", "objStr", {
								showDel: !_that.checkedit,
								showAdd: !_that.checkedit
							}, null, mainData)
						}
					}
					_that.$nextTick(function() {
						_that.$refs.autoform.initSelectVal('topinfo', "zposId")
						_that.$refs.autoform.initSelectIndex("InfoTitle","businessTripTypeId")
						if (!_that.$refs.autoform.formdata.infoId) {
							_that.$refs.autoform.formdata.infoId = _that.userId
							_that.$refs.autoform.formdata.infoName = _that.userName
							_that.getUserSalaryPosInfo(_that.userId)
						}
						_that.$refs.autoform.initSelectIndex("InfoTitle", "privateCarPublicUseId")
					})
				}, options)
			},
			formSubmit() {
				let _that = this;
				_that.formdata.updateBottomFileFlag = true
				delete _that.formdata.bottomFileUpload
				delete _that.formdata.bottomFileList
				if (Object.prototype.toString.call(_that.$refs.autoform.formdata.bottomFileList) == "[object String]") {
					_that.formdata.bottomFileListStr = _that.$refs.autoform.formdata.bottomFileList || ''
				} else {
					_that.formdata.bottomFileListStr = JSON.stringify(_that.$refs.autoform.formdata.bottomFileList ||
					[]) || ''
				}
				delete _that.formdata.bottomFileUpload
				delete _that.formdata.bottomFileList
				let length = _that.subEditorObj["workOfficeInfo"].workList.length
				let title = _that.$refs.autoform.getEditorTitle("workOfficeInfo", "objStr")
				if (_that.formdata.objStr) {
					let dataList = JSON.parse(_that.formdata.objStr)
					for (let index in dataList) {
						if (!dataList[index].fileList) {
							delete dataList[index].fileList
						}
					}
					_that.formdata.objStr = JSON.stringify(dataList)
				}

				if (length < 1) {
					_that.om.toast("请配置" + title)
					return
				}
				
				_that.om.request(
					"tworkoffice/verifyClockInRecord",
					{
						infoId: _that.formdata.infoId,
						objStr: _that.formdata.objStr
					}
				).then(res=>{
					if (res.succeed) {
					    if (res.value) {
							uni.showModal({
								title: '提示',
								content: res.value,
								showCancel: true,
								success(res){
									if(res.confirm){
										_that.om.formSave('tworkoffice/save',_that.formdata,_that)
									}
								}
							})
					    } else {
					        _that.om.formSave('tworkoffice/save',_that.formdata,_that)
					    }
					} else {
						_that.om.toast(res.tip)
					}
				})
			},
		},
		onUnload() {
			let _that = this
			uni.removeStorage({
				key: _that.defaultDataCache
			})
			//#ifdef APP-PLUS
			if (_that.$refs.autoform) {
				for (var fieldId in _that.subEditorObj) {
					uni.removeStorage({
						key: getWorkCacheKey(fieldId)
					});
				}
			}
			//#endif
		},
		onLoad(options) {
			this.initValue.userinfoId = this.userId
			this.initLoad(options)
			uni.setStorageSync('omBusinessTripType', '39415')
			this.businessTripTypeCode = '39415'
		},
		onShow() {
			let _that = this;
			if (_that.$refs.autoform) {
				for (var fieldId in _that.subEditorObj) {
					var editor = _that.subEditorObj[fieldId];
					uni.getStorage({
						key: getWorkCacheKey(fieldId),
						success: function(res) {
							editor.workList = res.data;
							uni.removeStorage({
								key: getWorkCacheKey(fieldId)
							});
						}
					});
				}
				uni.getStorage({
					key: _that.infoCacheKey,
					success: (res) => {
						if (res.data) {
							let d = res.data
							let formdata = _that.$refs.autoform.formdata
							formdata.infoId = d.id
							_that.userId1 = d.id
							formdata.infoName = d.username
							_that.getUserSalaryPosInfo(d.id)
							uni.removeStorage({
								key: _that.infoCacheKey
							})
						}
					}
				})
				uni.getStorage({
					key: _that.InstCacheKey,
					success: (res) => {
						if (res.data) {
							let d = res.data
							let formdata = _that.$refs.autoform.formdata
							formdata.costInstId = d.id
							formdata.costInstName = d.instName
							uni.removeStorage({
								key: _that.InstCacheKey
							})
						}
					}
				});
				uni.getStorage({
					key: _that.sameOutUserCache,
					success: (res) => {
						if (res.data) {
							let d = res.data
							uni.setStorage({
								key: _that.defaultDataCache,
								data: d
							})
							let formdata = _that.$refs.autoform.formdata;
							if (d.length) {
								let idList = []
								let nameList = []
								let sameOutUserIds = ''
								for (let index in d) {
									if (d[index].id == formdata.infoId) {
										errorModal(_that, '提示系信息', '请勿选择当前出差人作为同行人', () => {
											uni.removeStorage({
												key: _that.sameOutUserCache
											})
											uni.removeStorage({
												key: _that.defaultDataCache
											})
										})
										return
									}
									idList.push(d[index].id)
									nameList.push(d[index].username)
								}

								let idStr = idList.map(e => e).join(",")
								let nameStr = nameList.map(e => e).join(",");

								formdata.sameOutUserId = idStr
								formdata.sameOutUserName = nameStr

							}
							uni.removeStorage({
								key: _that.sameOutUserCache
							})
						}
					}
				});
			}
		}
	}
</script>

<style>
</style>